import {
  Button,
  Modal,
  Row,
  Col,
  Menu,
  Dropdown,
  Tree,
  Tag,
  Table,
} from 'antd';
import { DownOutlined } from '@ant-design/icons';
import React, { useCallback, useEffect, useState } from 'react';
import styles from './index.less';

import { getOrgTree, getByMgtorg, choosePage } from '@/net/common/index';
import Const from '@/utils/Const';

import InfiniteScroll from 'react-infinite-scroller';

interface treeDataParams {
  title: string;
  key: string | number | undefined;
  children?: Array<treeDataParams>;
}
interface userListParams {
  name: string;
  id: string | number;
}

class PrivateData {
  // type 1 人员 - 管理机构 2 用户 - 管理机构
  static typeMap = new Map().set(1, '人员').set(2, '用户');
  static getListMap = new Map().set(1, getByMgtorg).set(2, choosePage);
  static idType = new Map()
    .set(1, 'mgtScopeOrgIds')
    .set(2, 'employeeOrganizationId');
  static paramsObj: any = {
    pageNumber: 1,
    pageSize: 10,
    employeeOrganizationId: [],
    mgtScopeOrgIds: [],
  };
  static loading = true;
  static dataSource: any[] = [];
  static dealArr = (arr: any) => {
    let _arr: any[] = [];
    if (!Array.isArray(arr)) return _arr;
    for (let item of arr) {
      let _item: treeDataParams = {
        title: item.name,
        key: item.id,
        children: [],
      };
      if (Array.isArray(item.children) && item.children.length !== 0) {
        _item.children = PrivateData.dealArr(item.children);
      } else {
        _item.children = [];
      }
      _arr.push(_item);
    }
    return _arr;
  };
  static resetPrivateData = () => {
    PrivateData.paramsObj = {
      pageNumber: 1,
      pageSize: 10,
      employeeOrganizationId: [],
      mgtScopeOrgIds: [],
    };
    PrivateData.loading = true;
    PrivateData.dataSource = [];
  };
}

export default (props: any) => {
  const {
    isModalVisible,
    handleSubmit,
    handleCancel,
    type,
    userList = [],
  } = props;
  console.log(props);
  // 部门列表
  const [departmentList, setDepartmentList] = useState<any[]>([]);
  // 当前的部门
  const [department, setDepartment] = useState<any>({
    name: '',
    nameEn: '',
    value: '',
    children: [],
  });
  //树状checkKeys集合
  const [departmentTreeCheckKeys, setDepartmentTreeCheckKeys] = useState<
    React.Key[]
  >([]);
  // 已选择的人员用户数组
  const [tagList, setTagList] = useState<userListParams[]>([]);

  // table数据
  const [dataSource, setDataSource] = useState<any[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<any[]>([]);
  // 是否有更多数据
  const [hasMore, setHasMore] = useState<boolean>(true);

  // 获取机构树
  const getDepartmentTree = useCallback(async () => {
    let res = await getOrgTree({
      orgId: '',
      orgType: 1, // 0 全部 1 管理机构 2 工作机构
    });
    console.log('获取管理机构树', res);
    if (res.code === Const.successCode) {
      const arr = res.data || [];
      if (Array.isArray(arr) && arr.length === 1) {
        const data = arr[0].children || [];
        let _departmentList = [];
        for (let item of data) {
          let children = PrivateData.dealArr(item.children);
          _departmentList.push({
            name: item.name || '',
            nameEn: item.nameEn || '',
            value: item.id || '',
            children,
          });
        }
        console.log(_departmentList, '_departmentList');
        setDepartmentList(_departmentList);
        setDepartment(_departmentList[0]);
        setDepartmentTreeCheckKeys(_departmentList[0].value);
      }
    }
  }, []);

  useEffect(() => {
    if (isModalVisible) {
      getDepartmentTree();
      setTagList(userList);
      let _selectedRowKeys = [];
      for (let item of userList) {
        _selectedRowKeys.push(item.id);
      }
      setSelectedRowKeys(_selectedRowKeys);
    } else {
      PrivateData.resetPrivateData();
      setDataSource([]);
      setSelectedRowKeys([]);
      setHasMore(true);
      setTagList([]);
    }
  }, [isModalVisible]);

  // 获取列表数据
  const getList = useCallback(
    (list: any, isFromMore?: boolean) => {
      PrivateData.loading = true;
      const idList: string = PrivateData.idType.get(+type);
      if (!isFromMore) PrivateData.paramsObj[idList] = list;
      PrivateData.getListMap
        .get(+type)(PrivateData.paramsObj)
        .then((res: any) => {
          console.log(res, '列表');
          PrivateData.loading = false;
          if (res && res.code && res.code === Const.successCode) {
            let arr = res.data || [];
            if (arr.length >= PrivateData.paramsObj.pageSize) {
              setHasMore(true);
            } else {
              setHasMore(false);
            }
            let oldArr = [...PrivateData.dataSource];
            PrivateData.dataSource = [...oldArr, ...arr];
            setDataSource([...oldArr, ...arr]);
          }
        });
    },
    [type, dataSource],
  );

  // 切换一级部门
  const menuItemClick = useCallback(
    (item) => {
      if (department.value === item.value) return;
      setDepartmentTreeCheckKeys([item.value]);
      PrivateData.resetPrivateData();
      setDepartment(item);
      setTagList([]);
      setSelectedRowKeys([]);
      getList([item.value]);
      setDataSource([]);
    },
    [department],
  );

  // 部门下拉选择
  const menu = () => (
    <Menu>
      {departmentList.map((item, index) => (
        <Menu.Item key={index} onClick={() => menuItemClick(item)}>
          {item.name}
        </Menu.Item>
      ))}
    </Menu>
  );

  // 结构树选中
  const onCheck = useCallback(
    (checkedKeys, info: any) => {
      console.log('onCheck', departmentTreeCheckKeys, checkedKeys, info);
      let concatCheckedKeys = [...departmentTreeCheckKeys, ...checkedKeys];
      PrivateData.resetPrivateData();
      if (concatCheckedKeys.length !== 0) {
        getList(concatCheckedKeys);
        setDepartmentTreeCheckKeys(concatCheckedKeys);
      } else {
        setDataSource([]);
      }
    },
    [menuItemClick],
  );

  // 关闭标签
  const closeTag = useCallback(
    (e, id) => {
      e.preventDefault();
      const _tagList = tagList.filter((item) => item.id !== id);
      setTagList([..._tagList]);
      let _selectedRowKeys = selectedRowKeys.filter((item) => item !== id);
      setSelectedRowKeys([..._selectedRowKeys]);
    },
    [tagList, selectedRowKeys],
  );

  // 加载更多
  const handleInfiniteOnLoad = useCallback(() => {
    if (PrivateData.loading || !hasMore) return;
    PrivateData.paramsObj.pageNumber++;
    getList([], true);
  }, [hasMore]);

  // rowSelection object indicates the need for row selection
  const rowSelection = {
    onChange: (selectedRowKeys: React.Key[], selectedRows: any[]) => {
      console.log(
        `selectedRowKeys: ${selectedRowKeys}`,
        'selectedRows: ',
        selectedRows,
      );
      let notHaveIdArr: any[] = [];
      for (let item of dataSource) {
        if (selectedRowKeys.indexOf(item.id) === -1) notHaveIdArr.push(item.id);
      }
      let _selectedRows = [...tagList];
      let _tagIdList = [];
      for (let item of tagList) {
        _tagIdList.push(item.id);
      }
      for (let item of selectedRows) {
        if (_tagIdList.indexOf(item.id) === -1) {
          _tagIdList.push(item.id);
          _selectedRows.push({
            id: item.id,
            name: item.name,
          });
        }
      }
      _selectedRows = _selectedRows.filter(
        (item) => notHaveIdArr.indexOf(item.id) === -1,
      );
      _tagIdList = _tagIdList.filter(
        (item) => notHaveIdArr.indexOf(item) === -1,
      );
      setSelectedRowKeys(_tagIdList);
      setTagList(_selectedRows);
    },
    selectedRowKeys: selectedRowKeys,
  };

  const columns = [
    {
      title: '序号',
      render: (text: any, record: any, index: any) => `${index + 1}`,
    },
    {
      title: '用户名',
      dataIndex: 'name',
    },
    {
      title: '创建者',
      dataIndex: 'createdBy',
    },
    {
      title: '工号',
      dataIndex: 'employeeCode',
    },
    {
      title: '归属组织',
      dataIndex: 'nameFullPath',
    },
  ];

  const handleOk = useCallback(() => {
    const result = {
      tags: tagList,
      departmentTreeCheckKeys,
    };
    handleSubmit(result);
  }, [tagList]);

  return (
    <Modal
      title={`${PrivateData.typeMap.get(type)}管理`}
      visible={isModalVisible}
      onOk={handleOk}
      onCancel={handleCancel}
      destroyOnClose
      width={'80%'}
    >
      <Row className={styles.rowContent}>
        <Col span={6}>
          <Dropdown overlay={menu}>
            <div className={styles.colBoxName}>
              一级部门 - {department.name} <DownOutlined />
            </div>
          </Dropdown>
          <Tree
            checkable
            onCheck={onCheck}
            selectable={false}
            treeData={department.children}
          />
        </Col>
        <Col span={12} className={styles.colMiddleBox}>
          <div className={styles.colBoxName}>{`选择${PrivateData.typeMap.get(
            type,
          )}`}</div>
          <div className={styles.scrollContent}>
            <InfiniteScroll
              initialLoad={false}
              loadMore={handleInfiniteOnLoad}
              hasMore={hasMore}
              useWindow={false}
            >
              <Table
                dataSource={dataSource}
                rowKey="id"
                rowSelection={{
                  type: 'checkbox',
                  ...rowSelection,
                }}
                columns={columns}
                pagination={false}
              />
            </InfiniteScroll>
          </div>
        </Col>
        <Col span={6} className={styles.colRightBox}>
          <div className={styles.colBoxName}>{`已选择${PrivateData.typeMap.get(
            type,
          )}`}</div>
          <div className={styles.tagTitle}>已选择{tagList.length}项</div>
          <div className={styles.tagContent}>
            {tagList.map((item) => (
              <Tag key={item.id} closable onClose={(e) => closeTag(e, item.id)}>
                {item.name}
              </Tag>
            ))}
          </div>
        </Col>
      </Row>
    </Modal>
  );
};
